// -*- coding: utf-8 -*- 
/**
 * Project: AlgorithmsLearn
 *
 * @author: yanking
 * Create time: 2022-03-18 16:12
 * IDE: IntelliJ IDEA
 * Introduction:
 */
package com.LeetCodeT.ArraysTrain;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class Intersection {
    /**
     * 返回两个数组的交集 -> 交集元素不可以重复
     *
     * @param nums1
     * @param nums2
     * @return
     */
    public int[] intersection(int[] nums1, int[] nums2) {
        /*
            使用HashSet 存储遍历两个列表元素
         */
        Set<Integer> set1 = new HashSet<Integer>();
        Set<Integer> set2 = new HashSet<Integer>();
        for (int i = 0; i < nums1.length; i++) {
            set1.add(nums1[i]);
        }
        for (int i = 0; i < nums2.length; i++) {
            set2.add(nums2[i]);
        }
        HashSet<Integer> tmp = new HashSet<>();
        Iterator<Integer> iterator = set1.iterator();
        while (iterator.hasNext()) {
            Integer next = iterator.next();
            if (!set2.contains(next)) {
                tmp.add(next);
            }
        }
        set1.removeAll(tmp);
        int[] res = new int[set1.size()];
        int k = 0;
        for (Integer set : set1) {
            res[k++] = set;
        }

        return res;
    }
}
